package com.ponxu.mb;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.ponxu.config.Properties;
import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.mb.exception.BlogException;
import com.ponxu.utils.Lang;

/**
 * Blog全局配置
 * 
 * @author xwz
 * 
 */
public class Global {
	private static final Log LOG = LogFactory.getLog();
	private static final String GLOBAL_FILE = "/global.properties";
	private static Properties props;

	static {
		reloadProperties();
	}

	public static void reloadProperties() {
		props = new Properties();
		InputStream in = Global.class.getResourceAsStream(GLOBAL_FILE);
		try {
			props.load(in);
			in.close();
		} catch (IOException e) {
			LOG.fatal("Load Global Properties Failed! %s", GLOBAL_FILE);
			throw new BlogException(e);
		}
	}

	public static String read(String key) {
		return props.getProperty(key);
	}

	public static long readLong(String key) {
		String v = read(key);
		if (Lang.isNotEmpty(v)) {
			return Long.parseLong(v.trim());
		}
		return 0;
	}

	public static int readInt(String key) {
		String v = read(key);
		if (Lang.isNotEmpty(v)) {
			return Integer.parseInt(v.trim());
		}
		return 0;
	}

	public static boolean readBoolean(String key) {
		return Lang.convertBoolean(read(key));
	}

	public static Object write(String key, Object value) {
		return props.setProperty(key, String.valueOf(value));
	}

	public static void save() {
		try {
			OutputStream out = new FileOutputStream(Global.class.getResource(
					GLOBAL_FILE).getFile());
			props.save(out);
		} catch (IOException e) {
			LOG.warn("Load Global Properties Failed! %s", GLOBAL_FILE);
			throw new BlogException(e);
		}
	}
}
